from datetime import datetime

from common.response import Response, response2dict
from models import Information, db
from util.jsonUtil import information2dict


def getInformation():
    informations=Information.query.all()
    code = "200"
    msg = "查询成功"
    data = [information2dict(information) for information in informations]
    response = Response(code, msg, data)
    return response2dict(response)


def addInformation(information):
    db.session.add(information)
    db.session.commit()
    date=datetime.now()
    information.time=date
    code = "200"
    msg = "添加成功"
    data = information2dict(information)
    response = Response(code, msg, data)
    return response2dict(response)


def getInformationById(id):
    information_list = Information.query.filter_by(user_id=id).all()
    if len(information_list) == 0:
        code = "404"
        msg="信息为空"
        data=[information2dict(information) for information in information_list]
        response = Response(code, msg, data)
        return response2dict(response)
    code = "200"
    msg = "查询成功"
    data = [information2dict(information) for information in information_list]
    response = Response(code, msg, data)
    return response2dict(response)


def getinformationBySort(id,sort):
    informations = Information.query.filter_by(user_id=id).all()
    information_list=[]
    for information in informations:
        if sort in information.sort:
            information_list.append(information)
    if len(information_list) == 0:
        code = "404"
        msg = "信息为空"
        data = [information2dict(information) for information in information_list]
        response = Response(code, msg, data)
        return response2dict(response)
    code = "200"
    msg = "搜索成功"
    data = [information2dict(information) for information in information_list]
    response = Response(code, msg, data)
    return response2dict(response)
